package com.fjp.heartguard.app.weight.pop

import android.content.Context
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import com.fjp.heartguard.R
import com.fjp.heartguard.app.data.bean.AppVersion
import com.heartguard.appupdate.listener.OnDownloadListener
import com.heartguard.appupdate.manager.HttpDownLoadManager
import com.luck.picture.lib.thread.PictureThreadUtils
import com.lxj.xpopup.core.CenterPopupView
import java.io.File

class UpdateVersionPop(context: Context, val appVersion: AppVersion, val clickInstall: InstallClickListener) : CenterPopupView(context), OnDownloadListener {
    interface InstallClickListener {
        fun onClick(file: File)
    }

    lateinit var progressBar: ProgressBar
    lateinit var installBtn: Button
    lateinit var downloadTv: TextView
    lateinit var updateDesTv: TextView
    lateinit var updateIconIv: ImageView
    lateinit var apkFile: File
    override fun getImplLayoutId(): Int {
        return R.layout.pop_update_version
    }

    override fun onCreate() {
        super.onCreate()
        updateIconIv = findViewById<ImageView>(R.id.updateIconIv)
        updateDesTv = findViewById<TextView>(R.id.updateDesTv)
        downloadTv = findViewById<TextView>(R.id.downloadTv)
        progressBar = findViewById<ProgressBar>(R.id.progressBar)
        installBtn = findViewById<Button>(R.id.installBtn)
        installBtn.setOnClickListener {
            clickInstall.onClick(apkFile)
            dismiss()
        }
        context.externalCacheDir?.let {
            HttpDownLoadManager(it.path).download(appVersion.download_url, "heartguard.apk", this)
        }


    }

    override fun start() {
    }

    override fun onDownLoading(max: Int, progress: Int) {
        val curr = (progress / max.toDouble() * 100.0).toInt()
        PictureThreadUtils.runOnUiThread {
            downloadTv.setText("正在下载${curr}%")
            progressBar.progress = curr
        }
    }

    override fun cancel() {
        PictureThreadUtils.runOnUiThread {
            dismiss()
        }
    }

    override fun done(apk: File) {
        apkFile = apk
        installBtn.visibility = View.VISIBLE
        progressBar.visibility = View.GONE
        downloadTv.visibility = View.GONE
        updateDesTv.setText("下载完成")
        updateIconIv.setBackgroundResource(R.drawable.update_completed)
    }

    override fun error(e: Exception) {
        PictureThreadUtils.runOnUiThread {
            dismiss()
        }

    }
}